import os
import sys
import subprocess
import traceback

class SSHController:
    def __init__(self, 
        port=2200, 
        rsa_key="/etc/ssh_host_rsa_key",
        dsa_key="/etc/ssh_host_dsa_key"):
        
        self.__port = port
        self.__rsa_key = rsa_key
        self.__dsa_key = dsa_key
        
        
    def start_sshd(self):
        self._start_mac_sshd()
        
    def stop_sshd(self):
        self._stop_mac_sshd()
        
    def _stop_mac_sshd(self):
        file_path = os.path.dirname(traceback.extract_stack()[-1][0])
        plist_filename = os.path.join(file_path, "ssh.plist")
        
        result = subprocess.Popen(
            ["sudo",
            "launchctl",
            "unload",
            "-wF",
            plist_filename
            ],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT
        )
        
        for line in result.stdout:
            print >> sys.stderr, line
        
    def _start_mac_sshd(self):
        #Set up the sshd plist for os x
        file_path = os.path.dirname(traceback.extract_stack()[-1][0])
        plist_template_filename = os.path.join(file_path, "ssh.plist.template")
        plist_template = open(plist_template_filename)
        plist_filename = os.path.abspath(os.path.join(file_path, "ssh.plist"))
        plist = open(plist_filename, "w")
        plist_string = plist_template.read()
        plist.write(plist_string)
        print plist_filename
        
        result = subprocess.Popen(
            ["sudo",
            "launchctl",
            "load",
            "-wF",
            plist_filename
            ],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT
        )
        
        for line in result.stdout:
            print >> sys.stderr, line
        
if __name__ == "__main__":
    SSHController().start_sshd()
        